package com.alm.token.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.bean.CandyOrderDetilData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BaseView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.Utils;
import com.chad.library.adapter.base.BaseViewHolder;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.encode.CodeCreator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
//import com.uuzuche.lib_zxing.activity.CodeUtils;

public class CandyOrderDetailActivity extends BaseActivity implements BaseView<CandyOrderDetilData> {

    @BindView(R.id.tv_topshow)
    TextView tvTopshow;
    @BindView(R.id.tv_expireshow)
    TextView tvExpireshow;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.btn_candyshare)
    TextView btnCandyshare;
    @BindView(R.id.btn_candyreturn)
    TextView btnCandyReturn;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodataViewBody;
    private CandyOrderDetilData.DataBean dataBean;
    private List<CandyOrderDetilData.DataBean.JiluBean> jiluBeans = new ArrayList<>();
    private RefreshLoadMoreManager<CandyOrderDetilData.DataBean.JiluBean> manager;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_candy_order_detail;
    }

    @Override
    protected void initVariables() {
        new ActionBarHelper(this).setTitle(getString(R.string.mine_hint_candydetail));
    }

    @Override
    protected void initViews() {
        nodataViewBody.setVisibility(View.VISIBLE);
        initManager();
    }

    private void initManager() {
        OrderAdapter adapter = new OrderAdapter(this);
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .build();
        recyclerView.setNestedScrollingEnabled(false);
    }

    @Override
    protected void loadData() {
        preenter.getCandyOrderDetil(String.valueOf(getIntent().getIntExtra("id", 0)));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_candyshare:
                if (dataBean != null) {
                    showpopwindow(dataBean.getQrcode());
                }
                break;
            case R.id.btn_candyreturn:
                preenter.getCandyReturnData(String.valueOf(getIntent().getIntExtra("id", 0)));
                break;
            case R.id.tv_savebitmap:
                if (bodyBitmap == null) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                //存储权限
                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    if (saveImageToGallery(CandyOrderDetailActivity.this, bodyBitmap, CommonUtil.getStringDate() + getString(R.string.profile_hint_item35))) {
                                        showToast(getString(R.string.profile_hint_item15));
                                        tvSavebitmap.setText(getString(R.string.profile_hint_item16));
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });

                break;
            case R.id.tv_copy:
                if (xiazaiuri.isEmpty()) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                copyWalletAddress(xiazaiuri);
                break;
        }

    }

    @Override
    public void getData(CandyOrderDetilData candyOrderDetilData) {
/**
 * totallist : 3
 * moneyname : G12
 * getlist : 1
 * qrcode : http://v.babih.com/api/candy/home?mycode=51
 * jilu : [{"money":2.1993,"time":1553506357000,"username":"xfj002"}]
 * totalmoney : 9.0
 * getmoney : null
 */
        if (candyOrderDetilData.getStatus() == 0) {
            if(candyOrderDetilData.getData()==null){
                showToast(candyOrderDetilData.getMsg());
                finish();
                return;
            }
            dataBean = candyOrderDetilData.getData();
            tvTopshow.setText(getString(R.string.invite_hint_candy_detail_top, dataBean.getGetlist() + "/" + dataBean.getTotallist(), dataBean.getGetmoney() + "/" + dataBean.getTotalmoney() + dataBean.getMoneyname()));
            if (dataBean.getStatus() == 2||dataBean.getStatus() == 3) {//到期结束,退款
                tvExpireshow.setVisibility(View.VISIBLE);
                tvExpireshow.setText(getString(R.string.invite_hint_candy_expire, CommonUtil.saveToPoint4WithNo(dataBean.getTotalmoney() - dataBean.getGetmoney()) + dataBean.getMoneyname()));
            }

            btnCandyshare.setOnClickListener(dataBean.getStatus() == 0 ? this : null);
            btnCandyshare.setBackground(getResources().getDrawable(dataBean.getStatus() == 0 ? R.drawable.gradient_btn : R.drawable.gradient_btn_unclick));
            btnCandyshare.setText(
                    dataBean.getStatus() == 1 ? getString(R.string.invite_hint_candy_finished)
                            : dataBean.getStatus() == 2  ? getString(R.string.invite_hint_candy_expire).split(",")[0]+getString(R.string.invite_hint_candy_expire_zd)
                            :dataBean.getStatus() == 3 ? getString(R.string.invite_hint_candy_expire).split(",")[0]+getString(R.string.invite_hint_candy_expire_sd)
                            : getString(R.string.invite_hint_candycode));

            btnCandyReturn.setOnClickListener(dataBean.getStatus() == 0 ? this : null);
            btnCandyReturn.setVisibility(dataBean.getStatus() == 0 ? View.VISIBLE : View.GONE);

            if (dataBean.getJilu() != null && dataBean.getJilu().size() != 0) {
                jiluBeans = dataBean.getJilu();
                nodataViewBody.setVisibility(View.GONE);
                for (CandyOrderDetilData.DataBean.JiluBean jiluBean : jiluBeans) {
                    jiluBean.setLayoutId(OrderAdapter.LAYOUT_ID);
                }
                manager.setData(jiluBeans);
            } else {
                nodataViewBody.setVisibility(View.VISIBLE);
            }
        } else showToast(candyOrderDetilData.getMsg());
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    public class OrderAdapter extends BaseAdapter<CandyOrderDetilData.DataBean.JiluBean> {

        public static final int LAYOUT_ID = R.layout.item_candylist_base;

        public OrderAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, CandyOrderDetilData.DataBean.JiluBean item, int itemType) {
            /**
             * money : 2.1993
             * time : 1553506357000
             * username : xfj002
             */
            helper.setText(R.id.tv_name0, item.getUsername());
            helper.setText(R.id.tv_staue1, "" + CommonUtil.saveToPoint4WithNo(item.getMoney()));
            helper.setText(R.id.tv_staue,  dataBean.getMoneyname());
            helper.setText(R.id.tv_phone0, CommonUtil.getDateTimeFromMillisecond(item.getTime()));
            helper.setVisible(R.id.tv_time0, false);
        }

    }


    PopupWindow p;

    private void showpopwindow(String uri) {
        xiazaiuri = uri;
        final View inflate = View.inflate(this, R.layout.layout_candy_qrcode, null);
        imgAdressqrcode = inflate.findViewById(R.id.img_adressqrcode);
        lyQrcodeBody = inflate.findViewById(R.id.ly_qrcodebody);
        if (LanguageUtils.getSetIndex() == 1) {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg1));
        } else if (LanguageUtils.getSetIndex() == 3){
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg13));
        }else if (LanguageUtils.getSetIndex() == 4){
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg14));
        }else {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg_en1));
        }

        LinearLayout lyQrcodeBodySmall = inflate.findViewById(R.id.ly_qrqdbody_small);
        if (LanguageUtils.getSetIndex() == 1) {
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg2));
        } else if (LanguageUtils.getSetIndex() == 3){
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg23));
        }else if (LanguageUtils.getSetIndex() == 4){
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg24));
        }else {
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg2_en));
        }

        inflate.findViewById(R.id.leftItem).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (p != null && p.isShowing()) {
                    p.dismiss();
                    p = null;
                }
            }
        });

        TextView tvright = inflate.findViewById(R.id.rightItem);
        tvright.setText("More");
        tvright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopwindow1();
            }
        });


        TextView title = inflate.findViewById(R.id.centerItem);
        title.setText(getString(R.string.profile_hint_item35).replace(".jpg", ""));

        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels * 3 / 4;         // 屏幕宽度（像素）
        int height = dm.heightPixels * 3 / 4;       // 屏幕高度（像素）

        p = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        p.setTouchable(true);
        p.setFocusable(true);
        p.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color_cccccc)));
        p.setAnimationStyle(R.style.Animleft);
        p.showAtLocation(inflate, Gravity.CENTER, 0, 0);
        p.showAsDropDown(inflate, 100, 100);
        initAddressQRCode();

    }

    PopupWindow popWindow;

    private void showPopwindow1() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.activity_invite_select, null);

        tvSavebitmap = popView.findViewById(R.id.tv_savebitmap);
        tvCopy = popView.findViewById(R.id.tv_copy);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, Utils.dp2px(this, 130));
//            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
            popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
            tvSavebitmap.setOnClickListener(this);
            tvCopy.setOnClickListener(this);
        }

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    LinearLayout lyQrcodeBody;
    ImageView imgAdressqrcode;
    TextView tvCopy, tvSavebitmap;
    //    private QRCodeEncode.Builder builder;
    private Bitmap qrCodeBitmap = null;
    private Bitmap bodyBitmap = null;
    private String xiazaiuri = "";

    private void initAddressQRCode() {
//        layoutView(lyQrcodeBody,CommonUtil.px2dip(this,470),CommonUtil.px2dip(this,600));

        qrCodeBitmap = CodeCreator.createQRCode(xiazaiuri,
                CommonUtil.dip2px(this, 160),
                CommonUtil.dip2px(this, 160),
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        imgAdressqrcode.setImageBitmap(qrCodeBitmap);

        bodyBitmap = CommonUtil.getBitMapFromView(lyQrcodeBody);
    }


    private void copyWalletAddress(String msg) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            // 创建普通字符型ClipData

            ClipData mClipData = ClipData.newPlainText("Label", msg);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
        showToast(getString(R.string.profile_hint_item14));
        tvCopy.setText(getString(R.string.profile_hint_item14));
    }

    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap   要保存的图片
     * @param fileName 自定义图片名称
     * @return
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
        //系统相册目录
        String storePath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        LogUtil.e("storePath=" + storePath);
        // 保存图片至指定路径
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";


        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        LogUtil.e("file=" + file.toString());
        try {
            LogUtil.e("file1");
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
            LogUtil.e("file2");
            //发送广播通知系统图库刷新数据
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                LogUtil.e("file3");
                return true;
            } else {
                LogUtil.e("file4");
                return false;
            }
        } catch (IOException e) {
            LogUtil.e("file_err=" + e.toString());
            e.printStackTrace();
        }
        LogUtil.e("file5");
        return false;
    }
}
